/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers.Beans;

//Roy
//Import de varios facades Usados... 
import Entities.Employee;
import Entities.Student;
import Entities.User;
import Facades.EmployeeFacade;
import Facades.RolFacade;
import Facades.StudentFacade;
import Facades.UserFacade;
import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.inject.Named;
import javax.servlet.http.HttpSession;

/**
 *
 * @author jesus
 */
@Named(value = "loginBean")
@SessionScoped
public class LoginBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private String username;
    private String password;
    private boolean isLoggedIn;
    private boolean isAdmin;
    private boolean isEmployee;
    private boolean isStudent;
    //Para el Growwwwl
    private ExternalContext ex = FacesContext.getCurrentInstance().getExternalContext();
    //Las variables de session
    private HttpSession session = (HttpSession) ex.getSession(true);
    private User entity_User;
    @EJB
    private UserFacade ejbFacade_User;
    @EJB
    private StudentFacade ejbFacade_Student;
    @EJB
    private EmployeeFacade ejbFacade_Employee;
    //Mas de Growl
    private FacesContext ctx = FacesContext.getCurrentInstance();
    private String path = ctx.getExternalContext().getRequestContextPath();

    public LoginBean() {
    }

    public String login() {
        if (!username.isEmpty() & !password.isEmpty()) {
            entity_User = ejbFacade_User.FindUserAndPass(username, password);

            //REGISTRY FOUND... USER LOGGED...
            if (entity_User != null) {
                //if (entity_User == null) {
                //  entity_User = new User();


                entity_User.setLastLoginDate(new Date());
                entity_User.setPicture("default.png");
                //Storing to database
                ejbFacade_User.edit(entity_User);

                //Si es Estudiante
                if (entity_User.getRolidRol().getIdRol() == 2) {
                    session.setAttribute("name", ejbFacade_Student.FindbyUser(entity_User).getFullName());
                    session.setAttribute("idNumber", ejbFacade_Student.FindbyUser(entity_User).getIdNumber());
                }
                //Si es Empleado
                if (entity_User.getRolidRol().getIdRol() == 3) {
                    session.setAttribute("name", ejbFacade_Employee.FindbyUser(entity_User).getFullName());
                    session.setAttribute("idNumber", ejbFacade_Employee.FindbyUser(entity_User).getIdNumber());
                }

                if (entity_User.getRolidRol().getDescripcion().equals("Administrator")) {
                    isAdmin = true;
                }
                if (entity_User.getRolidRol().getDescripcion().equals("Student")) {
                    isStudent = true;
                }
                if (entity_User.getRolidRol().getDescripcion().equals("Employee")) {
                    isEmployee = true;
                }

                session.setAttribute("idUser", entity_User.getId());
                session.setAttribute("picture", entity_User.getPicture());
                session.setAttribute("email", entity_User.getEmail());
                session.setAttribute("idRol", entity_User.getRolidRol().getIdRol());
                session.setAttribute("rolDescription", entity_User.getRolidRol().getDescripcion());

                isLoggedIn = true;

                return "home.xhtml";
            }
            //No registrado/Encontrado
            else {
                //set the message to display when authentication fails  
                FacesContext.getCurrentInstance().addMessage("Login", new FacesMessage(ResourceBundle.getBundle("/Bundle").getString("InvalidUserandPassword")));
                return "index.xhtml";
            }
            
        } else {
            FacesContext.getCurrentInstance().addMessage("Login", new FacesMessage(ResourceBundle.getBundle("/Bundle").getString("TypeUserandPassword")));
            return null;
        }
    }

    public String logout() {
        isLoggedIn = false;
        isAdmin = false;
        isStudent = false;
        isEmployee = false;
        FacesContext context = FacesContext.getCurrentInstance();
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        try {
            context.getExternalContext().redirect(path);
        } catch (IOException e) {
            FacesContext.getCurrentInstance().addMessage("Login", new FacesMessage(e.getMessage()));
            Logger
                    .getLogger(LoginBean.class
                    .getName()).log(Level.SEVERE, null, e);
        }
        return path;

    }

    /**
     * An event listener for redirecting the user to login page if he/she is not
     * currently logged in
     *
     * @param event
     */
    public void verifyUseLogin(ComponentSystemEvent event) {
        if (!isLoggedIn) {
            doRedirect();
        }
    }

    /**
     * Method for redirecting a request
     *
     * @param url
     */
    private void doRedirect() {
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect(path);
        } catch (IOException e) {
            FacesContext.getCurrentInstance().addMessage("Login", new FacesMessage(e.getMessage()));
            Logger
                    .getLogger(LoginBean.class
                    .getName()).log(Level.SEVERE, null, e);
        }
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isLoggedIn() {
        return isLoggedIn;
    }

    public boolean isIsAdmin() {
        return isAdmin;
    }

    public boolean isIsStudent() {
        return isStudent;
    }

    public void setLoggedIn(boolean isLoggedIn) {
        this.isLoggedIn = isLoggedIn;
    }


    public boolean isIsEmployee() {
        return isEmployee;
    }

    public void setIsEmployee(boolean isEmployee) {
        this.isEmployee = isEmployee;
    }

    public User getEntity_User() {
        return entity_User;
    }

    public void setEntity_User(User entity_User) {
        this.entity_User = entity_User;
    }
    
    
}
